package com.etlmaster.executor.trans.core;

import java.lang.reflect.Constructor;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.etlmaster.executor.EtlMasterException;
import com.etlmaster.executor.StepMeta;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class RowStepMeta extends StepMeta{

	public RowStepMeta(String id, String name, String step_code,
			String sessionId, String paramStr) {
		super(id, name, step_code, sessionId, paramStr);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void loadParamsFromConfigTable() {
		// TODO Auto-generated method stub
		
	}

	protected void initProcessorList(String ruleArray,
			List<LineTransProcessor> ruleList, String funcType) throws EtlMasterException {
		String[] rules = ruleArray.split(",");
		for (String rule : rules) {
			Rule ruleInstance=((Map<String,Rule>)getVariable("rules")).get(rule);
			if (ruleInstance != null) {
				String colName = ruleInstance.getSourceCol();
				String tableName = ruleInstance.getSourceTable();
				String targetColName = ruleInstance.getTargetCol();
				String targetTabName = ruleInstance.getTargetTable();
				LineTransProcessor processor = null;
				Map<String, Map<String, Object>> changeCodes = (Map<String, Map<String, Object>>) ruleInstance
						.getFuncMaps().get(funcType);
				if (changeCodes == null) {
					continue;
				}
				Iterator it = changeCodes.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry entry = (Entry) it.next();
					String changeCode = (String) entry.getKey();
					String className = LineProcessor.getTrans_INST_CLASS_MAPP().get(changeCode);
					className=className.replace("Meta", "");
					if (className == null) {
						log("ERROR", "步骤指令{}错误，程序终止" + changeCode);
					} else {
						try {
							Class cls = Class.forName(className);
							Map paramStr = (Map) ((Map<String, Object>) ruleInstance
									.getFuncMaps().get(funcType))
									.get(changeCode);
							Constructor<LineTransProcessor> constructor = cls
									.getConstructor(Integer.class,
											String.class, String.class,
											String.class, String.class,
											String.class, Map.class, Map.class);
							processor = constructor.newInstance(-1, tableName,
									colName, targetTabName, targetColName,
									changeCode, paramStr, getVariables());
							ruleList.add(processor);
						} catch (Exception e) {
							log("ERROR", "生成转换实例时失败,{}",
									e.getMessage());
						}
					}
				}
			} else {
				log("ERROR", "未找到rule对应的规则信息,{}", rule);
				throw new EtlMasterException("未找到rule:" + rule + "对应的规则信息");
			}
		}
	}
}
